/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="trafficStrength"
    v-loading="loading"
    element-loading-spinner="el-icon-loading"
    :element-loading-background="loadingBg">
    <div class="left">
      <div class="lefttop">
        <div class="title">{{$t('openatc.devicemanager.flowStatistics')}}</div>
          <div class="choosePanel">
            <span v-for="(item, index) in chooseButtons"
                  :key="index">
              <span v-on:click="()=>updateStrengthChart(item.key)"
                    class="btn"
                    :class="{'btnFocus': item.active === true}">{{item.value}}</span>
            </span>
          </div>
          <div class="chart1" id="strength"></div>

      </div>
      <div class="leftbottom">
        <div class="title">{{$t('openatc.devicemanager.indexStatistics')}}</div>
        <div class="chart2" id="timing"></div>
      </div>
    </div>
  </div>
</template>
<script>
import * as echart from 'echarts'
import { getIntersectionStatistics } from '../../../../api/historydata.js'
import moment from 'moment'
import { getTheme } from '../../../../utils/auth'
export default {
  name: 'detailed-trafficstrength',
  components: {
  },
  props: {
    date: {
      type: Array
    },
    ASCID: undefined
  },
  data () {
    return {
      curTimeData: {},
      curStrengthData: {},
      timeSelIndex: -1,
      strSelIndex: -1,
      loading: false,
      loadingBg: '#202940',
      chooseButtons: [
        {
          key: 'flowStatistics',
          value: this.$t('openatc.devicemanager.flowStatistics'),
          active: true
        },
        {
          key: 'saturationStatistics',
          value: this.$t('openatc.devicemanager.saturationStatistics'),
          active: false
        }
      ],
      curChart: {
        key: 'flowStatistics',
        value: this.$t('openatc.devicemanager.flowStatistics')
      },
      periodicSeleted: undefined,
      strengthSeleted: undefined,
      Color: new Map([[0, '#43b4cf'], [1, '#c6bf72'], [2, '#5085d1'], [3, '#cc7966'], [4, '#537896'], [5, '#d39351'], [6, '#45ab89'], [7, '#a25768']]),
      defalultOpention2: {
        backgroundColor: getTheme() === 'light' ? '#FFFFFF' : '#202940',
        color: ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00'],
        // title: {
        //   text: 'Gradient Stacked Area Chart'
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            boundaryGap: false,
            axisLabel: {
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              },
              formatter: function (value, index) { // 坐标轴文字展示样式处理
              // return echart.format.formatTime('yyyy-MM-dd hh:mm:ss', value)
                return echart.format.formatTime('MM-dd hh:mm:ss', value)
              }
            },
            axisTick: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisTick: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            splitLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
              }
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
              }
            },
            axisLabel: {
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              }
            }
          }
        ],
        series: [
          {
            name: 'Line 1',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            // itemStyle: {
            //   normal: {
            //     color: 'red', // 图例的颜色
            //     lineStyle: {
            //       color: 'red'// 线的颜色
            //     }
            //   }
            // },
            areaStyle: {
              opacity: 0.8,
              color: new echart.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(128, 255, 165)'
                },
                {
                  offset: 1,
                  color: 'rgb(1, 191, 236)'
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: [140, 232, 101, 264, 90, 340, 250]
          },
          {
            name: 'Line 2',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echart.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(0, 221, 255)'
                },
                {
                  offset: 1,
                  color: 'rgb(77, 119, 255)'
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: [120, 282, 111, 234, 220, 340, 310]
          }
        ]
      }
    }
  },
  created () {
    this.setLoadingBg()
  },
  mounted () {
    this.initChart()
    this.refreshChart()
  },
  methods: {
    setLoadingBg () {
      this.loadingBg = getTheme() === 'light' ? '#fff' : '#202940'
    },
    changeBtnStyle (key) {
      // 选中按钮高亮
      this.chooseButtons.forEach(button => {
        button.active = false
        if (button.key === key) {
          button.active = true
        }
      })
    },
    updateStrengthChart (key) {
      this.changeBtnStyle(key)
      // 更新相位分布环图小标题
      this.curChart = this.chooseButtons.filter(btn => btn.key === key)[0]
      this.renderStrengthChart(key)
    },
    lockScreen () {
      this.loading = true
    },
    unlockScreen () {
      this.loading = false
    },
    initChart () {
      this.strengthChart = echart.init(document.getElementById('strength'), getTheme())
      this.timingChart = echart.init(document.getElementById('timing'), getTheme())
      this.InitStrengthChartEvent()
      this.InitTimeChartEvent()
      const _this = this
      window.onresize = function () {
        _this.strengthChart.resize()
        _this.timingChart.resize()
      }
    },
    ShowPanelStrength (selIndex) {
      if (this.strengthData === undefined || selIndex === undefined) return
      this.curStrengthData = this.alldata[selIndex]
    },
    ShowPanelRang (selIndex) {
      if (this.TimingData === undefined ||
      this.$refs.periodicPanel === undefined || selIndex === undefined) return
      this.curTimeData = this.TimingData[selIndex]
      this.$refs.periodicPanel.refreshRangChart()
    },
    InitStrengthChartEvent () {
      this.strengthChart.on('updateAxisPointer', event => {
        this.ShowPanelStrength(event.dataIndex)
      })

      this.strengthChart.on('click', event => {
        if (this.strengthData === undefined) return
        this.timingChart.dispatchAction({
          type: 'downplay',
          dataIndex: this.timeSelIndex
        })
        this.timeSelIndex = this.findIndexInTimeData(event.name)
        this.timingChart.dispatchAction({
          type: 'highlight',
          dataIndex: this.timeSelIndex
        })

        this.ShowPanelRang(this.timeSelIndex)
      })

      this.strengthChart.on('legendselectchanged', event => {
        // 点击图例取消某相位显示，对应的相位分布图也要取消该相位
        this.strengthSeleted = event.selected
      })
    },
    InitTimeChartEvent () {
      this.timingChart.on('updateAxisPointer', event => {
        this.ShowPanelRang(event.dataIndex)
      })

      this.timingChart.on('click', event => {
        if (this.TimingData === undefined) return
        this.curTimeData = this.TimingData[event.dataIndex]

        this.timingChart.dispatchAction({
          type: 'downplay',
          dataIndex: this.timeSelIndex
        })

        let date = event.name
        this.strengthChart.dispatchAction({
          type: 'downplay',
          dataIndex: this.strSelIndex
        })
        this.strSelIndex = this.findIndexInStrengthData(date)
        this.strengthChart.dispatchAction({
          type: 'highlight',
          dataIndex: this.strSelIndex
        })

        this.ShowPanelStrength(this.strSelIndex)
      })
      this.timingChart.on('legendselectchanged', event => {
        // 点击图例取消某相位显示，对应的周期分布图也要取消该相位
        this.periodicSeleted = event.selected
      })
    },
    findIndexInTimeData (date) {
      let XAxisList = this.getTimingXAxis(this.TimingData)
      // XAxisList = XAxisList.sort((val1, val2) => {
      //   return new Date(val1).getTime() > new Date(val2).getTime()
      // })
      for (let index = XAxisList.length - 1; index >= 0; --index) {
        let strDate = new Date(date)
        let timeDate = new Date(XAxisList[index])
        if (timeDate.getTime() < strDate.getTime()) { return index - 1 }
      }
      return -1
    },
    findIndexInStrengthData (date) {
      let XAxisList = this.getStrXAxis(this.strengthData)
      for (let index = 0; index < XAxisList.length; ++index) {
        let timeDate = new Date(date)
        let strDate = new Date(XAxisList[index])
        if (timeDate.getTime() < strDate.getTime()) { return index }
      }

      return -1
    },
    async refreshChart () {
      await this.getHistoryPattern()
      this.refreshStrengthChart()
      // this.refreshTimingChart()
      this.unlockScreen()
      this.changeBtnStyle('flowStatistics')
    },
    renderStrengthChart (key) {
      // 渲染
      this.strengthChart.clear()
      // 取最新时刻的相位数据，赋值给curStrengthData
      this.curStrengthData = this.alldata[this.alldata.length - 1]
      let opention2 = JSON.parse(JSON.stringify(this.defalultOpention2))
      this.resetStrengthOption(opention2, this.alldata, key)
      this.strengthChart.clear()
      this.strengthChart.setOption(opention2)
    },
    resetStrengthOption (opention2, alldata, key) {
      let legendData = []
      let xAxisData = []
      let seriesData0 = []
      let seriesData1 = []
      let name0 = this.$t('openatc.devicemanager.totalflow')
      let name1 = this.$t('openatc.devicemanager.averageflow')
      if (key === 'saturationStatistics') {
        name0 = this.$t('openatc.devicemanager.saturation')
        name1 = this.$t('openatc.devicemanager.greenusage')
        delete opention2.series[0].showSymbol
        delete opention2.series[0].areaStyle
        delete opention2.series[0].lineStyle
        delete opention2.series[0].emphasis
        delete opention2.series[1].showSymbol
        delete opention2.series[1].areaStyle
        delete opention2.series[1].lineStyle
        delete opention2.series[1].emphasis
      }
      if (key === 'timing') {
        name0 = this.$t('openatc.devicemanager.congestionindex')
        name1 = this.$t('openatc.devicemanager.imbalanceindex')
        delete opention2.series[0].showSymbol
        delete opention2.series[0].areaStyle
        delete opention2.series[0].lineStyle
        delete opention2.series[0].emphasis
        delete opention2.series[1].showSymbol
        delete opention2.series[1].areaStyle
        delete opention2.series[1].lineStyle
        delete opention2.series[1].emphasis
      }
      if (key !== 'flowStatistics') {
      }
      for (let data of alldata) {
        let xdata = data.time
        let sdata0 = data.totalflow
        let sdata1 = data.averageflow
        if (key === 'saturationStatistics') {
          sdata0 = data.saturation
          sdata1 = data.greenusage
        }
        if (key === 'timing') {
          sdata0 = data.congestionindexdata
          sdata1 = data.imbalanceindexdata
        }

        xAxisData.push(xdata)
        seriesData0.push(sdata0)
        seriesData1.push(sdata1)
      }
      legendData = [name0, name1]
      opention2.legend.data = legendData
      opention2.xAxis[0].data = xAxisData
      opention2.series[0].data = seriesData0
      opention2.series[1].data = seriesData1
      opention2.series[0].name = name0
      opention2.series[1].name = name1
    },
    resetTimingOption (opention2, alldata, key) {
      let legendData = []
      let xAxisData = []
      let seriesData0 = []
      let seriesData1 = []
      let name0 = this.$t('openatc.devicemanager.congestionindex')
      let name1 = this.$t('openatc.devicemanager.imbalanceindex')
      for (let data of alldata) {
        let xdata = data.time
        let sdata0 = data.congestionindexdata
        let sdata1 = data.imbalanceindexdata
        if (key === 'saturationStatistics') {
          sdata0 = data.saturation
          sdata1 = data.greenusage
        }
        xAxisData.push(xdata)
        seriesData0.push(sdata0)
        seriesData1.push(sdata1)
      }
      legendData = [name0, name1]
      opention2.legend.data = legendData
      opention2.xAxis.data = xAxisData
      opention2.series[0].data = seriesData0
      opention2.series[1].data = seriesData1
      opention2.series[0].name = name0
      opention2.series[1].name = name1
    },
    refreshStrengthChart () {
      return this.getStrengthData().then(data => {
        this.alldata = JSON.parse(JSON.stringify(data))
        this.renderStrengthChart()
        this.refreshTimingChart()
      })
    },
    getStrXAxis (dataList) {
      let xAxisList = []
      for (let data of dataList) {
        xAxisList = [...xAxisList, data.date]
      }
      return [...new Set(xAxisList)]
    },
    getStrSeries (dataList) {
      let series = {
        name: this.curChart.value,
        type: 'line',
        connectNulls: true,
        itemStyle: {
          color: '#75B1E6'
        },
        areaStyle: {
          normal: {
            color: new echart.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                {offset: 0, color: '#77b3e8'},
                {offset: 0.2, color: '#7cb5e9'},
                {offset: 0.4, color: '#95c5ed'},
                {offset: 0.6, color: '#b1d3f1'},
                {offset: 0.8, color: '#c9e0f5'},
                {offset: 1, color: '#cee3f6'}
              ]
            ) // 区域的颜色
          }
        }
      }
      series.data = dataList.map(item => {
        return [item.date, item.value]
      })
      return series
    },
    getLineAnchorSeries () {
      let anchor = [
        [moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss'), 0],
        [moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss'), 0]
      ]
      let anchorSeries = {
        name: 'anchor',
        type: 'line',
        showSymbol: false,
        data: anchor,
        itemStyle: {normal: {opacity: 0}},
        lineStyle: {normal: {opacity: 0}}
      }
      return anchorSeries
    },
    refreshTimingChart () {
      this.TimingData = this.alldata
      let opention2 = {
        backgroundColor: getTheme() === 'light' ? '#FFFFFF' : '#202940',
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']
        },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          boundaryGap: false,
          axisLabel: {
            textStyle: {
              color: getTheme() === 'light' ? '#666666' : '#B9BABF'
            },
            formatter: function (value, index) { // 坐标轴文字展示样式处理
              // return echart.format.formatTime('yyyy-MM-dd hh:mm:ss', value)
              return echart.format.formatTime('MM-dd hh:mm:ss', value)
            }
          },
          axisTick: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          axisLine: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisTick: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          axisLine: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          splitLine: {
            lineStyle: {
              color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
            }
          },
          axisLabel: {
            textStyle: {
              color: getTheme() === 'light' ? '#666666' : '#B9BABF'
            }
          }
        },
        series: [{
          name: 'line1',
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: 'line'
        }, {
          name: 'line2',
          data: [420, 532, 501, 534, 690, 630, 620],
          type: 'line'
        }]
      }
      this.resetTimingOption(opention2, this.alldata, 'timing')
      this.timingChart.clear()
      this.timingChart.setOption(opention2)
    },
    setChartStyle (option) {
      let xAxis = option.xAxis[0]
      let yAxis = option.yAxis[0]
      if (!xAxis || !yAxis) {
        return option
      }
      let targetXAxis = {
        axisTick: {
          lineStyle: {
            color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
          }
        },
        axisLine: {
          lineStyle: {
            color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
          }
        },
        axisLabel: {
          textStyle: {
            color: getTheme() === 'light' ? '#666666' : '#B9BABF'
          },
          formatter: function (value, index) { // 坐标轴文字展示样式处理
            return echart.format.formatTime('MM-dd hh:mm:ss', value)
          }
        }
      }
      let targetYAxis = {
        axisTick: {
          lineStyle: {
            color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
          }
        },
        axisLine: {
          lineStyle: {
            color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
          }
        },
        axisLabel: {
          textStyle: {
            color: getTheme() === 'light' ? '#666666' : '#B9BABF'
          }
        },
        splitLine: {
          lineStyle: {
            color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
          }
        },
        splitArea: {
          show: true,
          areaStyle: {
            color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
          }
        }
      }
      xAxis = Object.assign(targetXAxis, xAxis)
      yAxis = Object.assign(targetYAxis, yAxis)
    },
    getTimingLegend (dataList) {
      let lergeList = []

      for (let data of dataList) {
        let rang1Data = data.rang1.map(item => {
          return item.phasename
        })
        let rang2Data = data.rang2.map(item => {
          return item.phasename
        })
        lergeList = [...lergeList, ...rang1Data, ...rang2Data]
      }

      return [...new Set(lergeList)]
    },
    getTimingXAxis (dataList) {
      return dataList.map(item => {
        return item.date
      })
    },
    getHistoryPattern () {
      let params = {
        beginTime: moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss'),
        agentid: this.ASCID
      }
      this.lockScreen()
      return new Promise((resolve, reject) => {
        getIntersectionStatistics(params).then(res => {
          this.unlockScreen()
          if (!res.data.success) {
            reject(res.data.message)
          }
          if (!res && res.data && res.data.data && res.data.data.intestatistics && (res.data.data.intestatistics.length > 0)) {
            this.$message.info(this.$t('openatc.common.nodata'))
          } else {
            this.HistoryPatternData = res
          }
          resolve()
        }).catch(() => {
          console.log('getIntersectionStatistics error')
          this.unlockScreen()
        })
      })
    },
    getStrengthData () {
      return new Promise((resolve, reject) => {
        let res = JSON.parse(JSON.stringify(this.HistoryPatternData))
        let resData = []
        for (let data of res.data.data.intestatistics) {
          let date = moment(data['time']).format('YYYY-MM-DD HH:mm:ss')
          let congestionindexdata = this.getGradeData(data.congestionindex)
          let imbalanceindexdata = this.getGradeData(data.imbalanceindex)
          let phaseData = {
            date,
            // mode: data.data.mode,
            // control: data.data.control,
            // patternid: data.data.patternid,
            // cycle: data.data.cycle,
            // offset: data.data.offset,
            // syncTime: data.data.syncTime,
            // curTime: data.data.curTime,
            'time': date,
            'totalflow': data.totalflow,
            'averageflow': data.averageflow,
            'saturation': data.saturation,
            'occupyrate': data.occupyrate,
            'greenusage': data.greenusage,
            'congestionindex': data.congestionindex,
            'imbalanceindex': data.imbalanceindex,
            'congestionindexdata': congestionindexdata,
            'imbalanceindexdata': imbalanceindexdata
          }
          resData.push(phaseData)
        }
        resolve(resData)
      })
    },
    getGradeData (val) {
      let res = 0
      switch (val) {
        case 'A':
          res = 1
          break
        case 'B':
          res = 2
          break
        case 'C':
          res = 3
          break
        case 'D':
          res = 4
          break
        case 'E':
          res = 5
          break
      }
      return res
    },
    getRingId (phaseId, ringList) {
      let ringNum = -1
      for (let ringInfo of ringList) {
        if (ringInfo.sequence.indexOf(phaseId) > -1) {
          ringNum = ringInfo.num
          break
        }
      }

      return ringNum
    },

    getTimingData () {
      return new Promise((resolve, reject) => {
        let res = JSON.parse(JSON.stringify(this.HistoryPatternData))
        let resData = []
        for (let data of res.data.data) {
          let curTime = moment(data['time']).format('YYYY-MM-DD HH:mm:ss')
          let timeData = resData.find(val => curTime === val.date)
          if (timeData === undefined) {
            timeData = {
              date: curTime,
              rang1: [],
              rang2: []
            }
            resData.push(timeData)
          }
          if (data.data.phase === undefined) continue
          for (let phaseData of data.data.phase) {
            let info = {
              phasename: '相位' + phaseData.id,
              time: phaseData.split
            }
            let ringIndex = this.getRingId(phaseData.id, data.data.rings)
            if (ringIndex === 1) timeData.rang1.push(info)
            if (ringIndex === 2) timeData.rang2.push(info)
          }
          timeData.rang1.sort((val1, val2) => {
            return val1.phasename > val2.phasename
          })
          timeData.rang2.sort((val1, val2) => {
            return val1.phasename > val2.phasename
          })
          // 生成按环重复的颜色
          for (let i = 0; i < timeData.rang1.length; i++) {
            timeData.rang1[i].color = this.Color.get(i)
          }
          for (let i = 0; i < timeData.rang2.length; i++) {
            timeData.rang2[i].color = this.Color.get(i)
          }
        }
        resolve(resData)
      })
    }
  }
}
</script>
